package online.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Auther: 狼芒
 * @Date: 2021/10/3 17:35
 * @Descrintion:
 * @version: 1.0
 */
@Lazy
@Slf4j
@RestController
@RequestMapping("/shiro/")
public class ShiroController {


    @GetMapping("login")
    public String login(String userName, String password) {
        log.error("username: {}, password: {}", userName, password);
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        try {
            subject.login(token);
        } catch (UnknownAccountException accountException) {
            //账号错误
            return "userName error";
        } catch (IncorrectCredentialsException credentialsException) {
            //密码错误
            return "password error";
        } catch (Exception e) {
            return "500 异常";
        }
        return "login";
    }

    @GetMapping("anno")
    public String anno() {
        return "anno";
    }

    @GetMapping("authc")
    public String authc() {
        return "authc";
    }

    @GetMapping("user")
    public String user() {
        return "user";
    }

    @GetMapping("perms")
    public String perms() {
        return "perms";
    }

    @GetMapping("role")
    @RequiresPermissions({"shiro:role"})
    public String role() {
        return "role";
    }


    @GetMapping("exit")
    public String exit() {
        //在这里执行退出系统前需要清空的数据
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "exit";
    }


}
